import os.path
from fastapi import APIRouter, File, UploadFile, HTTPException, status, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from price_analysis.core.config import settings
from price_analysis.core.models import db_helper, IncomingSO
from price_analysis.api_v1.incoming_so import schemas
from price_analysis.api_v1.incoming_so import crud
from price_analysis.api_v1.incoming_so.dependencies import incoming_so_by_id
from price_analysis.utils import file_support

router = APIRouter(tags=["incoming_so"])


@router.post(
    "/",
    status_code=status.HTTP_201_CREATED,
)
async def upload_files(
        files: list[UploadFile] = File(...),
        session: AsyncSession = Depends(db_helper.get_async_session),
) -> dict:
    if not files:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                            detail="Файлы не получены сервером")

    if not os.path.exists(settings.incoming_path):
        os.makedirs(settings.incoming_path)

    for file in files:
        file_id: int = await crud.create_incoming_so(session=session,
                                                     file_name=file.filename)
        await file_support.write_file(file_id, file)

    return {"result": "success"}


@router.get("/", response_model=list[schemas.IncomingSo])
async def get_all_incoming(
        session: AsyncSession = Depends(db_helper.get_async_session), ):
    return await crud.get_all_incoming_so(session=session)


@router.put("/{idx}/")
async def update_incoming_so(
        so_update: schemas.IncomingSoUpdate,
        incoming_so: IncomingSO = Depends(incoming_so_by_id),
        session: AsyncSession = Depends(db_helper.get_async_session),
):
    return await crud.update_incoming_so(
        session=session,
        incoming_so=incoming_so,
        so_update=so_update,
    )


@router.patch("/{idx}/")
async def update_incoming_partial(
        so_update: schemas.IncomingSoUpdatePartial,
        incoming_so: IncomingSO = Depends(incoming_so_by_id),
        session: AsyncSession = Depends(db_helper.get_async_session),
):
    return await crud.update_incoming_so(
        session=session,
        incoming_so=incoming_so,
        so_update=so_update,
        partial=True,
    )


@router.delete(
    "/{idx}/",
    response_model=schemas.IncomingSoDelete,
    status_code=status.HTTP_200_OK,
)
async def delete_incoming_so(
        incoming_so: IncomingSO = Depends(incoming_so_by_id),
        session: AsyncSession = Depends(db_helper.get_async_session),
):
    await file_support.remove_file(incoming_so.id, incoming_so.file_name)

    return await crud.delete_incoming_so(session=session,
                                         incoming_so=incoming_so)
